package cn.mumzone.pos.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;

import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.loading.button.LoadingButton;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.DisplayUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.pos.R;
import cn.mumzone.pos.model.MemberEntity;
import cn.mumzone.pos.presenter.BabyAddOrModifyPresenter;
import cn.mumzone.pos.presenter.contract.BabyAddOrModifyContract;

public class ACT_AddOrModifyBaby extends BaseActivity<BabyAddOrModifyPresenter> implements BabyAddOrModifyContract.View {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_baby_name)
    EditText etBabyName;
    @BindView(R.id.et_select_baby_birthday)
    EditText etSelectBabyBirthday;
    @BindView(R.id.rg_gender)
    RadioGroup rgGender;
    @BindView(R.id.et_baby_height)
    EditText etBabyHeight;
    @BindView(R.id.et_baby_weight)
    EditText etBabyWeight;
    @BindView(R.id.rg_production_type)
    RadioGroup rgProductionType;
    @BindView(R.id.lb_save)
    LoadingButton lbSave;

    private String selectGender = "0";

    private MemberEntity.BabysBean baby;

    private String babyId = "";

    private String memberId;

    private int labour = 0;

    private TimePickerView birthdayPickerView;

    @BindView(R.id.tv_baby_name_title)
    TextView tvBabyNameTitle;
    @BindView(R.id.tv_baby_birthday_title)
    TextView tvBabyBirthdayTitle;
    @BindView(R.id.tv_gender_title)
    TextView tvGenderTitle;


    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        baby = (MemberEntity.BabysBean) extras.getSerializable("baby");
        memberId = extras.getString("memberId");
    }

    @Override
    protected void initEventAndData() {


        SpannableString babyNameTitle = new SpannableString("* 宝宝小名");
        babyNameTitle.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvBabyNameTitle.setText(babyNameTitle);

        SpannableString babyBirthdayTitle = new SpannableString("* 宝宝生日");
        babyBirthdayTitle.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvBabyBirthdayTitle.setText(babyBirthdayTitle);

        SpannableString babyGenderTitle = new SpannableString("* 性别");
        babyGenderTitle.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvGenderTitle.setText(babyGenderTitle);

        etBabyName.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});

        initBirthdayPickerDialog();

        if (baby == null) {//新增
            tvTitle.setText("新增宝宝信息");
            lbSave.setText("确认添加宝宝");
        } else {//修改

            babyId = baby.getId();

            tvTitle.setText("修改宝宝信息");
            lbSave.setText("保存");

            etBabyName.setText(baby.getName());

            etSelectBabyBirthday.setText(AppDateUtil.getTimeStamp(baby.getBirthday(), AppDateUtil.YYYY_MM_DD));

            if (baby.getGender() == 0) {
                rgGender.check(R.id.rb_gender_man);
            } else {
                rgGender.check(R.id.rb_gender_women);
            }

            etBabyHeight.setText(baby.getHeight());
            etBabyHeight.setSelection(etBabyHeight.getText().length());

            etBabyWeight.setText(baby.getWeight());
            etBabyWeight.setSelection(etBabyWeight.getText().length());


            if (baby.getLabour() == 0) {
                rgProductionType.check(R.id.rb_production_zc);
            } else if (baby.getLabour() == 1) {
                rgProductionType.check(R.id.rb_production_sc);
            } else {
                rgProductionType.check(R.id.rb_production_pfc);
            }
        }

        rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_gender_man:
                        selectGender = "0";
                        break;
                    case R.id.rb_gender_women:
                        selectGender = "1";
                        break;
                }
            }
        });

        rgProductionType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_production_zc:
                        labour = 0;
                        break;
                    case R.id.rb_production_sc:
                        labour = 1;
                        break;
                    case R.id.rb_production_pfc:
                        labour = 2;
                        break;
                }
            }
        });

        etBabyName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    etBabyName.post(new Runnable() {
                        @Override
                        public void run() {
                            etBabyName.setSelection(etBabyName.getText().length());
                        }
                    });
                }
            }
        });

        etBabyHeight.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    etBabyHeight.post(new Runnable() {
                        @Override
                        public void run() {
                            etBabyHeight.setSelection(etBabyHeight.getText().length());
                        }
                    });
                }
            }
        });
        etBabyWeight.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    etBabyWeight.post(new Runnable() {
                        @Override
                        public void run() {
                            etBabyWeight.setSelection(etBabyWeight.getText().length());
                        }
                    });
                }
            }
        });
    }


    /**
     * 初始化生日时间选择器
     */
    private void initBirthdayPickerDialog() {
        Calendar nowDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(1999, 0, 1);
        Calendar endDate = Calendar.getInstance();
        birthdayPickerView = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                birthdayPickerView.dismiss();
                etSelectBabyBirthday.setText(AppDateUtil.getDateToString(date.getTime(), AppDateUtil.YYYY_MM_DD));
            }
        }).isDialog(true).isCyclic(false).setOutSideCancelable(true)
                .setType(new boolean[]{true, true, true, false, false, false})
                .setDate(nowDate)
                .setRangDate(startDate, endDate)
                .build();
        birthdayPickerView.getDialog().getWindow().setLayout(DisplayUtil.dip2px(mContext, 500),
                WindowManager.LayoutParams.WRAP_CONTENT);
    }

    @Override
    protected int getLayout() {
        return R.layout.act_add_or_modify_baby;
    }


    @OnClick(value = {R.id.iv_back, R.id.et_select_baby_birthday, R.id.lb_save})
    public void toggleEvent(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.et_select_baby_birthday:
                birthdayPickerView.getDialog().show();
                break;
            case R.id.lb_save:
                if (!mPresenter.isInputLegal(etBabyName.getText().toString(),
                        etSelectBabyBirthday.getText().toString())) {
                    return;
                }
                if (baby == null) {
                    lbSave.startLoading("确认添加宝宝");
                } else {
                    lbSave.startLoading("保存");
                }
                mPresenter.createNewBaby(etBabyName.getText().toString(), etSelectBabyBirthday.getText().toString(),
                        etBabyHeight.getText().toString(), etBabyWeight.getText().toString(), selectGender, babyId,
                        memberId, String.valueOf(labour));
                break;
        }
    }

    @Override
    public void onCreateOrModifyBabyInfoSuccess(MemberEntity.BabysBean baby, boolean isAppend) {
        if (isAppend) {
            PosToast.INSTANCE.makeToast(this, PosToast.ToastType.TOAST_TYPE_SQUARE,
                    PosToast.ToastSquareLevel.ALERT_SUCCESS_SQUARE, "添加成功", false);
        } else {
            PosToast.INSTANCE.makeCheckMarkToast(this, "已保存");
        }
        Intent intent = new Intent();
        intent.putExtra("baby", baby);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    @Override
    public void onCreateOrModifyBabyInfoFailed(boolean isAppend) {
        if (isAppend) {
            PosToast.INSTANCE.makeToast(this, PosToast.ToastType.TOAST_TYPE_SQUARE,
                    PosToast.ToastSquareLevel.ALERT_FAIL_SQUARE, "添加失败", false);
        } else {
            PosToast.INSTANCE.makeCheckMarkToast(this, "保存失败");
        }
        if (baby == null) {
            lbSave.stopLoading("确认添加宝宝");
        } else {
            lbSave.stopLoading("保存");
        }
    }
}
